<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>SpringBoot常用注解 | Yeding's Blog</title><meta name="keywords" content="Hexo，博文"><meta name="author" content="叶町"><meta name="copyright" content="叶町"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="SpringBoot常用注解总结">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot常用注解">
<meta property="og:url" content="https://www.yeding.top/post/5e47ee7383cc/index.html">
<meta property="og:site_name" content="Yeding&#39;s Blog">
<meta property="og:description" content="SpringBoot常用注解总结">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/86587640_p0.png">
<meta property="article:published_time" content="2020-12-31T07:26:02.000Z">
<meta property="article:modified_time" content="2020-12-31T08:09:54.000Z">
<meta property="article:author" content="叶町">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="SpringBoot">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/86587640_p0.png"><link rel="shortcut icon" href="/img/webicon.jpg"><link rel="canonical" href="https://www.yeding.top/post/5e47ee7383cc/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="msvalidate.01" content="278990AE0B56A7C826F87D7039A44A00"/><meta name="baidu-site-verification" content="code-c3G2TgtwfW"/><meta name="google-site-verification" content="_ae3149Ou1MfIkiKfOmwwj3AqiMp6ahEt9MT8YTVmtY"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'SpringBoot常用注解',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-12-31 16:09:54'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://testingcf.jsdelivr.net/gh/Lost-Swords/ImageLibrary/css/index.min.css"><link rel="stylesheet" href="//at.alicdn.com/t/font_2829204_gazvsq5039v.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Yeding's Blog" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "/image/loading.gif" data-lazy-src="https://s1.ax1x.com/2020/09/13/w0t8qe.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">10</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">12</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">4</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/86587640_p0.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Yeding's Blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">SpringBoot常用注解</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-12-31T07:26:02.000Z" title="发表于 2020-12-31 15:26:02">2020-12-31</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-12-31T08:09:54.000Z" title="更新于 2020-12-31 16:09:54">2020-12-31</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>7分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h4 id="springbootapplication"><a class="markdownIt-Anchor" href="#springbootapplication"></a> @SpringBootApplication</h4>
<p>核心注解。包括**@Configuration**，<strong>@EnableAutoConfiguration</strong>，<strong>@ComponentScan</strong>。</p>
<h4 id="configuration"><a class="markdownIt-Anchor" href="#configuration"></a> @Configuration</h4>
<p>从spring3.0开始用于定义配置类，可替换xml配置文件，该类中包含被@Bean注解的方法， 这些方法将会被<strong>AnnotationConfigApplicationContext</strong>或<strong>AnnotationConfigWebApplicationContext</strong>类进行扫描，并用于构建bean定义，初始化Spring容器。</p>
<h4 id="enableautoconfiguration"><a class="markdownIt-Anchor" href="#enableautoconfiguration"></a> @EnableAutoConfiguration</h4>
<p>实现**@Configuration<strong>注解的类中bean的自动装配。 帮助SpringBoot应用将所有符合条件的</strong>@Configuration**配置都加载到当前SpringBoot，并创建对应配置类的Bean，并把该Bean实体交给spring容器进行管理。</p>
<h4 id="componentscan"><a class="markdownIt-Anchor" href="#componentscan"></a> @ComponentScan</h4>
<p>默认装配标识了**@Controller**，<strong>@Service</strong>，<strong>@Repository</strong>，<strong>@Component</strong>注解的类到spring容器中。</p>
<h4 id="bean"><a class="markdownIt-Anchor" href="#bean"></a> @Bean</h4>
<p>Spring的@Bean注解用于方法上，该方法会产生一个Bean对象，然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次，随后这个Spring将会将这个Bean对象放在自己的IOC容器中。</p>
<h4 id="conditional"><a class="markdownIt-Anchor" href="#conditional"></a> @Conditional</h4>
<p>设置产生bean的条件，只有满足了该条件，bean才能正常创建。防止因对象为实例化等原因而产生的空指针或其他异常。与**@Bean**搭配使用，如 @Conditional(TestCondition.class) 意味着仅当TestCondition存在于ClassPath中时才生效，一般使用他的分支。</p>
<p>常见conditional注解</p>
<p><strong>@ConditionalOnBean</strong> 框架中存在某个Bean时生效</p>
<p><strong>@ConditionalOnMissingBean</strong> 在Bean不存在时生效</p>
<p><strong>@ConditionalOnClass</strong>框架中存在某个Class时生效</p>
<p><strong>@ConditionalOnMissingClass</strong>在Class不存在时生效</p>
<p><strong>@ConditionalOnWebApplication</strong> 当前是web环境</p>
<p><strong>@ConditionalOnNotWebApplication</strong> 当前不是web环境</p>
<p><strong>@ConditionalOnProperty</strong> 当前框架中是否包含特定的属性</p>
<p><strong>@ConditionalOnJava</strong> 当前是否存在某个Java版本</p>
<h4 id="mapperscan"><a class="markdownIt-Anchor" href="#mapperscan"></a> @MapperScan</h4>
<p>mybatis的注解，通过使用@MapperScan可以指定要扫描的Mapper类的包的路径，比如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@MapperScan(basePackages=&#123;&quot;com.yeding.dao&quot;&#125;)</span></span><br></pre></td></tr></table></figure>
<p>在启动类使用该注解后无需在mapper类中加上**@mapper**</p>
<h4 id="servletcomponentscan"><a class="markdownIt-Anchor" href="#servletcomponentscan"></a> @ServletComponentScan</h4>
<p>在启动类上使用该注解后，Servlet、Filter、Listener可以直接通过**@WebServlet**、<strong>@WebFilter</strong>、<strong>@WebListener</strong>注解自动注册</p>
<p>####@Component、@Repository、@Service、@Controller</p>
<p>我们一般使用 <strong>@Autowired</strong>注解让 Spring 容器帮我们自动装配 bean。要想把类标识成可用于 <strong>@Autowired</strong> 注解自动装配的 bean 的类,可以采用以下注解实现：</p>
<ul>
<li><strong>@Component</strong> ：通用的注解，可标注任意类为 <code>Spring</code> 组件。如果一个 Bean 不知道属于哪个层，可以使用**@Component** 注解标注。</li>
<li><strong>@Repository</strong> : 对应持久层即 Dao 层，主要用于数据库相关操作。</li>
<li><strong>@Service</strong> : 对应服务层，主要涉及一些复杂的逻辑，需要用到 Dao 层。</li>
<li><strong>@Controller</strong> : 对应 Spring MVC 控制层，主要用于接受用户请求并调用 Service 层返回数据给前端页面。</li>
</ul>
<p>可以用**@Service(“userDetailsService”)**等方式标注bean的id，默认id为首字母小写的类名。</p>
<h4 id="restcontroller-responsebody"><a class="markdownIt-Anchor" href="#restcontroller-responsebody"></a> @RestController、<strong>@ResponseBody</strong></h4>
<p><strong>@RestController</strong>注解是**@Controller<strong>和</strong>@ResponseBody**的合集,表示这是个控制器 bean,并且是将函数的返回值直 接填入 HTTP 响应体中,是 REST 风格的控制器。</p>
<p>单独使用 <strong>@Controller</strong>不加 <strong>@ResponseBody</strong>的话一般使用在要返回一个视图的情况，这种情况属于比较传统的 Spring MVC 的应用，对应于前后端不分离的情况。<strong>@Controller</strong> +<strong>@ResponseBody</strong> 返回 JSON 或 XML 形式数据</p>
<h4 id="requestmapping"><a class="markdownIt-Anchor" href="#requestmapping"></a> @RequestMapping</h4>
<p><strong>@RequestMapping</strong>是一个用来处理请求地址映射的注解，可用于类或方法上。用于类上，表示类中的所有响应请求的方法都是以该地址作为父路径。 它有方法级别注解和类级别注解两种类型。其属性为：</p>
<p>(1) <strong>value:</strong> 指定request的地址</p>
<p>(2) <strong>method:</strong> 指定请求的method类型， GET、POST、PUT、DELETE等</p>
<p>(3) **params:**指定request中包含的某些参数值，作为方法的输入</p>
<p>@RequestParam(value = “disable”, required = false)</p>
<pre><code>value 值为传入的参数

required 设置为 false，若传入的 value 为空值，则报错

required 设置为 true，若传入的 value 为空值，则返回 null 
</code></pre>
<p>(4) consumes: 指定处理请求的提交内容类型，例如 application/json, text/html;</p>
<p>(5) produces: 指定返回的内容类型，仅当request请求头中的(Accept)类型中包含该指定类型才返回</p>
<p>(6) headers: 指定request中包含某些指定的header值，让该方法处理请求</p>
<h4 id="getmapping-postmapping"><a class="markdownIt-Anchor" href="#getmapping-postmapping"></a> @GetMapping、@PostMapping…</h4>
<p>分别用于处理HTTP的get请求、post请求等。相当于指定method类型的**@RequestMapping**</p>
<h4 id="pathvariable和requestparam"><a class="markdownIt-Anchor" href="#pathvariable和requestparam"></a> @PathVariable和@RequestParam</h4>
<p>用于前端向后端传值时，获取url中的信息。</p>
<p>如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">GetMapping(<span class="string">&quot;/klasses/&#123;klassId&#125;/teachers&quot;</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Teacher&gt; <span class="title">getKlassRelatedTeachers</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">         <span class="meta">@PathVariable(&quot;klassId&quot;)</span> Long klassId,</span></span></span><br><span class="line"><span class="params"><span class="function">         <span class="meta">@RequestParam(value = &quot;type&quot;, required = false)</span> String type )</span> </span>&#123;</span><br><span class="line">...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果我们请求的 url 是：<strong>/klasses/{123456}/teachers?type=web</strong></p>
<p>那么我们服务获取到的数据就是：<strong>klassId=123456,type=web</strong>。</p>
<h4 id="requestbody"><a class="markdownIt-Anchor" href="#requestbody"></a> @RequestBody</h4>
<p>用于读取 Request 请求（可能是 POST,PUT,DELETE,GET 请求）的 body 部分并且<strong>Content-Type 为 application/json</strong> 格式的数据，接收到数据之后会自动将数据绑定到 Java 对象上去。系统会使用HttpMessageConverter或者自定义的HttpMessageConverter将请求的 body 中的 json 字符串转换为 java 对象。</p>
<h4 id="slf4j"><a class="markdownIt-Anchor" href="#slf4j"></a> @Slf4j</h4>
<blockquote>
<p>lf4j是一个日志标准，使用它可以完美的桥接到具体的日志框架，必要时可以简便的更换底层的日志框架，而不需要关心具体的日志框架的实现（slf4j-simple、logback等）</p>
</blockquote>
<p>该注解会自动创建<strong>loggger</strong>类的bean。并注入被注解的类，相当于<code>private final Logger log = LoggerFactory.getLogger(XXX.class)</code></p>
<p>idea需要安装lombok插件，否则会找不到注解生成的log变量从而报错。</p>
<h4 id="autowired-resource"><a class="markdownIt-Anchor" href="#autowired-resource"></a> @Autowired、@Resource</h4>
<p>实现容器的自动装配。spring会在应用上下文中为被注解的属性寻找其依赖的bean。是DI（依赖注入）的核心。</p>
<p>两者的异同：</p>
<p>1、<strong>@Autowired</strong>与**@Resource**都可以用来装配bean。都可以写在字段上，或写在setter方法上。</p>
<p>2、<strong>@Autowired</strong>默认按类型装配（属于spring规范），默认情况下必须要求依赖对象必须存在，如果要允许null 值，可以设置它的required属性为false，如：@Autowired(required=false) ，如果我们想使用名称装配可以结合@Qualifier注解进行使用</p>
<p>3、<strong>@Resource</strong>（属于J2EE规范），默认按照名称进行装配，名称可以通过name属性进行指定。如果没有指定name属性，当注解写在字段上时，默认取字段名进行按照名称查找，如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是，如果name属性一旦指定，就只会按照名称进行装配。</p>
<p>它们的作用相同都是用注解方式注入对象，但执行顺序不同。<strong>@Autowired</strong>先byType，<strong>@Resource</strong>先byName。</p>
<h4 id="value-configurationproperties-propertysource"><a class="markdownIt-Anchor" href="#value-configurationproperties-propertysource"></a> @value、 @ConfigurationProperties、 @PropertySource</h4>
<p>用于从配置文件中读取配置信息，以下默认配置文件为application.yml：</p>
<ul>
<li><strong>@value</strong>：用于读取比较简单的信息，功能很强大，除了能够注入配置信息，还可以直接注入普通字符串、操作系统属性、表达式结果甚至是其它Bean的属性等等，格式一般为： <strong>@Value(&quot;${property}&quot;)</strong> ，property为key值。</li>
<li><strong>@ConfigurationProperties</strong> ： 可以把同类的配置信息自动封装成实体类 ，用于大量属性值和配置文件的映射。格式一般为 <strong>@ConfigurationProperties(prefix = “library”)</strong> ,library为实体类的类名。</li>
<li><strong>@PropertySource</strong> ：用于指定配置文件，可以与**@value**和</li>
</ul>
<p><strong>@ConfigurationProperties</strong>搭配使用</p>
<p>详细分析参考：<a target="_blank" rel="noopener" href="https://cloud.tencent.com/developer/article/1497518">【小家Spring】Spring中读取配置的方式，@Value、@PropertySource、@ConfigurationProperties使用详解</a></p>
<h4 id="transactional"><a class="markdownIt-Anchor" href="#transactional"></a> @Transactional</h4>
<p>在方法上使用时表示该方法开启事务，在类上使用表示 该类的<strong>public</strong> 方法都配置相同的事务属性信息 。属于Spring提供的声明式事务的实现方式之一。注解的属性里可以设置事务的传播行为、隔离规则、回滚规则、事务超时、是否只读</p>
<p>详细分析参考<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/befc2d73e487">Spring 事务 – @Transactional的使用</a></p>
<h4 id="aspect"><a class="markdownIt-Anchor" href="#aspect"></a> @Aspect</h4>
<p>AOP的核心，作用是把当前类表示为一个切面供容器读取。必要时须再加上**@Component**</p>
<h4 id="pointcut"><a class="markdownIt-Anchor" href="#pointcut"></a> @Pointcut</h4>
<p>JoinPoint的集合，是程序中需要注入Advice的位置的集合，指明Advice要在什么样的条件下才能被触发，在程序中主要体现为书写切入点表达式。</p>
<p>Advice(通知、切面)： 某个连接点所采用的处理逻辑，也就是向连接点注入的代码， AOP在特定的切入点上执行的增强处理。</p>
<ol>
<li><strong>@Before</strong>： 标识一个前置增强方法，相当于BeforeAdvice的功能.</li>
<li><strong>@After</strong>： <strong>final增强</strong>，不管是抛出异常或者正常退出都会执行.</li>
<li><strong>@AfterReturning</strong>： 后置增强，似于AfterReturningAdvice, 方法正常退出时执行.</li>
<li><strong>@AfterThrowing</strong>： 异常抛出增强，相当于ThrowsAdvice.</li>
<li><strong>@Around</strong>： 环绕增强，相当于MethodInterceptor.</li>
</ol>
<p>~待续</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://www.yeding.top">叶町</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://www.yeding.top/post/5e47ee7383cc/">https://www.yeding.top/post/5e47ee7383cc/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://www.yeding.top" target="_blank">Yeding's Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a><a class="post-meta__tags" href="/tags/SpringBoot/">SpringBoot</a></div><div class="post_share"><div class="social-share" data-image="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/86587640_p0.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/gh/overtrue/share.js@master/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/50b39b8439ac/"><img class="prev-cover" src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/85572728_p0.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">绿皮书N2语法错题汇总</div></div></a></div><div class="next-post pull-right"><a href="/post/8cecd96a62b8/"><img class="next-cover" src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/86695978_p0.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">《标准日语语法》学习笔记——第一章绪论</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/dde04d069e3b/" title="JVM入门笔记"><img class="cover" src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/89478039_p0.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-18</div><div class="title">JVM入门笔记</div></div></a></div><div><a href="/post/08fb3a6a9e16/" title="Java多线程学习笔记"><img class="cover" src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/5f6496f6160a154a674aaf48.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-10-27</div><div class="title">Java多线程学习笔记</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "/image/loading.gif" data-lazy-src="https://s1.ax1x.com/2020/09/13/w0t8qe.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">叶町</div><div class="author-info__description">不要去了解我，也不要用因果报应咒骂我</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">10</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">12</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">4</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://space.bilibili.com/3169866"><i class="iconfont icon-bilibili-line"></i><span>关注我的B站账号</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://testingcf.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/weixinCode.jpg" target="_blank" title="微信"><i class="fab fa-weixin"></i></a><a class="social-icon" href="tencent://message/?uin=502818113&amp;Site=yedingBlog&amp;Menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://github.com/Lost-Swords" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:kanaumachi@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title=""><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content"><div class="social-button"> <a style="display:block;margin:.2rem 0;background-color:var(--btn-bg);color:var(--btn-color);text-align:center;line-height:2.4;;transition:all .3s;position:relative;z-index:1;" class="button--animated" href="https://yeding708.lofter.com/" rel="external nofollow noreferrer" target="_blank"><i class="iconfont icon-lofter"></i><span>关注我的LOFTER</span></a> </div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#springbootapplication"><span class="toc-text"> @SpringBootApplication</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#configuration"><span class="toc-text"> @Configuration</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#enableautoconfiguration"><span class="toc-text"> @EnableAutoConfiguration</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#componentscan"><span class="toc-text"> @ComponentScan</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#bean"><span class="toc-text"> @Bean</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#conditional"><span class="toc-text"> @Conditional</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#mapperscan"><span class="toc-text"> @MapperScan</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#servletcomponentscan"><span class="toc-text"> @ServletComponentScan</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#restcontroller-responsebody"><span class="toc-text"> @RestController、@ResponseBody</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#requestmapping"><span class="toc-text"> @RequestMapping</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#getmapping-postmapping"><span class="toc-text"> @GetMapping、@PostMapping…</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#pathvariable%E5%92%8Crequestparam"><span class="toc-text"> @PathVariable和@RequestParam</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#requestbody"><span class="toc-text"> @RequestBody</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#slf4j"><span class="toc-text"> @Slf4j</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#autowired-resource"><span class="toc-text"> @Autowired、@Resource</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#value-configurationproperties-propertysource"><span class="toc-text"> @value、 @ConfigurationProperties、 @PropertySource</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#transactional"><span class="toc-text"> @Transactional</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#aspect"><span class="toc-text"> @Aspect</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#pointcut"><span class="toc-text"> @Pointcut</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/post/a647efeab291/" title="【gal评】-交响乐之雨"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/synphonic_haku.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【gal评】-交响乐之雨"/></a><div class="content"><a class="title" href="/post/a647efeab291/" title="【gal评】-交响乐之雨">【gal评】-交响乐之雨</a><time datetime="2021-10-29T01:10:58.000Z" title="发表于 2021-10-29 09:10:58">2021-10-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/post/858ff2ba3ad9/" title="当我们在玩游戏时，我们在玩什么"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/genshin.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="当我们在玩游戏时，我们在玩什么"/></a><div class="content"><a class="title" href="/post/858ff2ba3ad9/" title="当我们在玩游戏时，我们在玩什么">当我们在玩游戏时，我们在玩什么</a><time datetime="2021-05-19T15:37:10.000Z" title="发表于 2021-05-19 23:37:10">2021-05-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/post/114244095f3c/" title="你好，Hexo"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/nier.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="你好，Hexo"/></a><div class="content"><a class="title" href="/post/114244095f3c/" title="你好，Hexo">你好，Hexo</a><time datetime="2021-04-16T09:21:58.000Z" title="发表于 2021-04-16 17:21:58">2021-04-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/post/709e1cd6d598/" title="日本语之森-N1语法（一）"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/dog_food.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="日本语之森-N1语法（一）"/></a><div class="content"><a class="title" href="/post/709e1cd6d598/" title="日本语之森-N1语法（一）">日本语之森-N1语法（一）</a><time datetime="2021-04-16T04:29:17.000Z" title="发表于 2021-04-16 12:29:17">2021-04-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/post/8cecd96a62b8/" title="《标准日语语法》学习笔记——第一章绪论"><img src= "/image/loading.gif" data-lazy-src="https://gcore.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/86695978_p0.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="《标准日语语法》学习笔记——第一章绪论"/></a><div class="content"><a class="title" href="/post/8cecd96a62b8/" title="《标准日语语法》学习笔记——第一章绪论">《标准日语语法》学习笔记——第一章绪论</a><time datetime="2021-01-03T23:18:59.000Z" title="发表于 2021-01-04 07:18:59">2021-01-04</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 - 2022 By 叶町</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><span>CDN BY <a target="_blank" rel="noopener" href="https://www.jsdelivr.com/">jsdelivr</a></span><br><div  style="display:flex;justify-content:center;align-items:center"><span>本网站由 </span><a href=https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral><img height="30" src= "/image/loading.gif" data-lazy-src="https://testingcf.jsdelivr.net/gh/Lost-Swords/ImageLibrary/img/upyun_logo.png" alt="又拍云"></a><span>提供CDN加速</span></div></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page@5/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'hello-cloudbase-4g4zs9fdc78abf63',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: 'hello-cloudbase-4g4zs9fdc78abf63',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.jsdelivr.net/npm/twikoo@1/dist/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !false) {
    if (false) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'hello-cloudbase-4g4zs9fdc78abf63',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo@1/dist/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (false) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><script src="https://testingcf.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js"></script><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>